#include "StrategyPlatform/Config.h"
#include "tinyxml/tinyxml.h"

StrategyPlatformConfig::StrategyPlatformConfig()
{

}

StrategyPlatformConfig::~StrategyPlatformConfig()
{

}

int StrategyPlatformConfig::ReLoad()
{
	return 0;
}

int StrategyPlatformConfig::Load()
{
	TiXmlDocument xmlDoc;
	if (!xmlDoc.LoadFile(STRATEGY_PLATFORM_CONFIG))
	{
		OUTPUT2(LOG_ERROR, "xml open fail:%s\n", xmlDoc.ErrorDesc());
		return FAIL;
	}

	TiXmlElement * root = xmlDoc.FirstChildElement("Platform");
	if (!root)
		return FATAL;

	TiXmlElement *node = root->FirstChild("Server")->ToElement();
	if (!node)
		return FATAL;
	sprintf_s(szQuoteURL, URL_LEN, node->Attribute("Quote"));
	sprintf_s(szTradeURL, URL_LEN, node->Attribute("Trade"));
	sprintf_s(szBrokerID, BROKER_ID_LENGTH, node->Attribute("BrokerID"));
	sprintf_s(szAccount, INVESTOR_ID_LENGTH, node->Attribute("AccountID"));
	sprintf_s(szPWD, PASSWORD_LENGTH, node->Attribute("Password"));

	node = root->FirstChild("Log")->ToElement();
	if (!node)
		return FATAL;
	nLogLevel = atoi(node->Attribute("level"));

	node = root->FirstChild("Sqlite")->ToElement();
	if (!node)
		return FATAL;
	sprintf_s(szSQLiteFile, URL_LEN, node->Attribute("file"));

	nInsCount = 0;
	node = root->FirstChild("Instrument")->ToElement();
	if (!node)
		return FATAL;
	const char * psvValue = 0;
	psvValue = node->Attribute("num");
	if (!psvValue)
	{
		return FATAL;
	}
	int nCount = atoi(node->Attribute("num"));
	for (size_t i = 0; i < nCount; i++)
	{
		char sz[33];
		sprintf_s(sz, 33, "Ins%d", i + 1);
		sprintf_s(szIns[nInsCount++], INS_ID_LENGTH, node->Attribute(sz));
	}


	node = root->FirstChild("Strategys")->ToElement();
	if (!node)
		return FATAL;

	plusCount = 0;
	memset(arrPlusDll, 0, sizeof(arrPlusDll));
	int num = atoi(node->Attribute("num"));
	for (int i = 1; i <= num && i <= ARRAY_SIZE; i++)
	{
		char szDll[URL_LEN], szTag[URL_LEN],szID[URL_LEN];
		sprintf_s(szDll, URL_LEN, "Strategy%d", i);
		sprintf_s(szTag, URL_LEN, "Tag%d", i);
		sprintf_s(szID, URL_LEN, "ID%d", i);
		tagStratePlus _plus;
		sprintf_s(_plus.szDll, URL_LEN, node->Attribute(szDll));
		sprintf_s(_plus.szTag, URL_LEN, node->Attribute(szTag));
		_plus.nId = atoi( node->Attribute(szID));

		arrPlusDll[plusCount++] = _plus;
	}
	
	node = root->FirstChild("Monitor")->ToElement();
	if (!node)		return FATAL;
	psvValue = node->Attribute("fSplippage");
	if (!psvValue)	return FATAL;
	m_monitorCfg.fSplippage = atof(psvValue);
	psvValue = node->Attribute("nCancelTime");
	if (!psvValue)	return FATAL;
	m_monitorCfg.nCancelTime = atoi(psvValue);

	bLoad = true;

	return SUCCESS;
}

char **StrategyPlatformConfig::GetIns(char **p)
{
	for (size_t i = 0; i < nInsCount; i++)
	{
		p[i] = szIns[i];
	}

	return p;
}

void StrategyPlatformConfig::GetSubIns(char *p[])
{
	for (size_t i = 0; i < nInsCount; i++)
	{
		p[i] = szIns[i];
	}
}
